import Base from './Base';
import { FillRectangleProps } from '../interface';

export default class FillRectangle extends Base {
  text: string;
  maxWidth: number;
  lineHeight: number;
  fontColor: string;
  font: string;
  textBaseline:
    | 'alphabetic'
    | 'bottom'
    | 'hanging'
    | 'ideographic'
    | 'middle'
    | 'top';
  paddingTop: number;
  paddingLeft: number;

  constructor(props: FillRectangleProps) {
    super(props);
    this.font = props.font;
    this.text = props.text;
    this.maxWidth = props.maxWidth;
    this.lineHeight = props.lineHeight;
    this.fontColor = props.fontColor;
    this.textBaseline = props.textBaseline;
    this.paddingTop = props.paddingTop;
    this.paddingLeft = props.paddingLeft;
  }

  fillWrapText() {
    const { ctx } = this;

    ctx.font = this.font;
    ctx.textBaseline = this.textBaseline;
    ctx.fillStyle = this.fontColor;

    // 字符分隔为数组
    const arrText = this.text.split('');
    if (!arrText) return;

    let line = '';
    const arrLineText: Array<string> = [];
    // 拼接文案
    arrText.forEach((item, index) => {
      let _line = line + item;
      let metrics = ctx.measureText(_line);
      let testWidth = metrics.width;
      if (testWidth > this.maxWidth && index > 0) {
        arrLineText.push(line);
        line = item;
        this.y += this.lineHeight;
      } else {
        line = _line;
      }
    });
    arrLineText.push(line);
    // 计算
    const textAllLineHeight = arrLineText.length * this.lineHeight;
    const heightSpace = Math.floor(
      (this.height - textAllLineHeight) / 2 + this.lineHeight / 5
    ); // 文字基线
    const left =
      arrLineText.length === 1
        ? (this.width - this.ctx.measureText(arrLineText[0]).width) / 2
        : this.paddingLeft;
    // 绘图
    arrLineText.forEach((item, index) => {
      ctx.fillText(
        item,
        this.x + left,
        this.y + heightSpace + index * this.lineHeight
      );
    });
  }

  paint() {
    this.ctx.fillStyle = this.bgColor;
    this.ctx.fillRect(this.x, this.y, this.width, this.height);
    this.fillWrapText();
  }
}